package com.example.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.entity.CourseOrder;
import com.example.api.entity.User;
import com.example.api.service.ICourseOrderService;
import com.example.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import java.util.List;

@Controller
public class BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private ICourseOrderService orderService;

    protected Boolean isBuyCourse(Long courseId, User user) {
        if (courseId == null || user == null) {
            return false;
        }
        QueryWrapper<CourseOrder> query = new QueryWrapper<>();
        query.eq("course_id",courseId)
                .eq("user_id",user.getId())
                .eq("order_status",2);

        List<CourseOrder> list = orderService.list(query);

        return ! list.isEmpty();
    }

    protected User getUser(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && StringUtils.hasText(authentication.getName())) {
            //存在此用户名
            String userName = authentication.getName();
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("name", userName);

            User user = userService.getOne(query);
            return  user;
        }
        return null;
    }
}
